#nullable enable

using System.Data.Common;
using Microsoft.Extensions.Options;
using PHMEE.EnergyEfficiency;
using TDengine.Data.Client;

namespace PHMEE.TDengineInfrastructure;

public abstract class BaseTdRepository : IAsyncDisposable
{
    private readonly TDengineOptions _tdengineOptions;

    protected TDengineConnection TDConnection;

    public BaseTdRepository(IOptionsSnapshot<TDengineOptions> tdengineOptions)
    {
        _tdengineOptions = tdengineOptions.Value;

        TDConnection = new TDengineConnection(_tdengineOptions.ConnectionString);
        TDConnection.Open();
    }

    /// <summary>
    /// 获取排序
    /// </summary>
    /// <param name="tdOrder"></param>
    /// <returns></returns>
    /// <exception cref="ArgumentOutOfRangeException"></exception>
    protected static string GetOrder(TdOrder tdOrder)
    {
        return tdOrder switch
        {
            TdOrder.Asc => "asc",
            TdOrder.Desc => "desc",
            _ => throw new ArgumentOutOfRangeException(nameof(tdOrder), tdOrder, "未知的排序方式")
        };
    }
    
    /// <summary>
    /// 从 reader 获取 DateTime 类型的数据，转换为 UTC 时间
    /// </summary>
    /// <param name="ordinal"></param>
    /// <param name="reader"></param>
    /// <returns></returns>
    protected static DateTime GetDateTimeUtc(string ordinal, DbDataReader reader)
    {
        var index = reader.GetOrdinal(ordinal);
        var dateTime = reader.GetDateTime(index);
        return dateTime.ToUniversalTime();
    }

    public async ValueTask DisposeAsync()
    {
        // websocket 模式下，手动 close connection 会在 dispose 时抛异常
        // await TDConnection.CloseAsync();
        await TDConnection.DisposeAsync();
    }
}